package com.yilin.tms.order.components;

import com.yilin.commons.util.ArrayUtil;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.annotation.Roboit;

import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.components.redis.RedisClient;
import com.yilin.tms.core.entity.order.dispatch.DispatchOrder;
import com.yilin.tms.core.entity.order.party.OrderDispatchTask;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.order.service.clearing.IGatherService;
import com.yilin.tms.order.service.order.IDispatchService;
import com.yilin.tms.order.service.order.IGoodsService;
import com.yilin.tms.order.service.order.IRobService;
import com.yilin.tms.order.service.order.ITransitService;
import com.yilin.tms.order.service.party.IOrderAppraiseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

@Service
public class OrderServiceTimerTask {
    Logger logger = LoggerFactory.getLogger(OrderServiceTimerTask.class);

    @Resource
    IOrderAppraiseService orderAppraiseService;
    @Resource
    IGatherService gatherService;
    @Resource
    IDispatchService dispatchService;




    @Resource
    IRobService robService;
    @Resource
    IGoodsService goodsService;
    @Resource
    ITransitService transitService;
    @Resource
    IUserRemote userRemote;

    /**
     * 定时任务 自动派单
     */
    @Scheduled(fixedDelay =  10 * 1000)
    @Roboit()
    public void taskDispatchOrder() {
        String suc = RedisClient.getInstance().hget("TIMER_TASK_KEY", "taskDispatchOrder");
        if (suc==null) {
            RedisClient.getInstance().hset("TIMER_TASK_KEY", "taskDispatchOrder","true");
            try {
                List<OrderDispatchTask> goingOrderDispatchTaskList = dispatchService.getGoingOrderDispatchTaskList();
                List<String> list = ArrayUtil.fieldAdd(goingOrderDispatchTaskList, OrderDispatchTask::getFromAccountId);
                if (!goingOrderDispatchTaskList.isEmpty()) {
                    List<Account> accountList = ParamUtil.isSuccess(userRemote.getAccountListByIds(String.join(",", list)));
                    ///开始任务
                    for (OrderDispatchTask orderDispatchTask : goingOrderDispatchTaskList) {
                        if (orderDispatchTask.getDispatchTaskStatus() == OrderDispatchTask.DispatchTaskStatus.complete) continue;
                        Account loginUser = ArrayUtil.getBy(accountList, obj -> obj.getId().equals(orderDispatchTask.getFromAccountId()));
                        if (loginUser == null) {
                            orderDispatchTask.setFailureReason("货主账户未找到！");
                            orderDispatchTask.setDispatchTaskStatus(OrderDispatchTask.DispatchTaskStatus.fail);
                            dispatchService.updateOrderDispatchTaskById(orderDispatchTask);
                            return;
                        }
                        //任务中断续传
                        List<String> alreadyList = new ArrayList<>();
                        if (orderDispatchTask.getAlreadyDispatchNos()!=null) {
                            alreadyList = ArrayUtil.initList(orderDispatchTask.getAlreadyDispatchNos().split(","));
                        }
                        List<String> totalList = ArrayUtil.initList(orderDispatchTask.getDispatchNos().split(","));
                        //只查询未完成的数据
                        List<DispatchOrder> dispatchOrderList = dispatchService.getDispatchOrderListByNo(totalList);
                        boolean isSuccess = true;
                        while (alreadyList.size() < totalList.size()){
                            DispatchOrder dispatchOrder = dispatchOrderList.get(alreadyList.size());
                            ReturnData<Object> returnData = dispatchService.taskDispatchOrder(loginUser,dispatchOrder);
                            if (returnData.isSuccess()){
                                alreadyList.add(dispatchOrder.getDispatchOrderNo());
                                orderDispatchTask.setAlreadyDispatchCount(alreadyList.size());
                                orderDispatchTask.setAlreadyDispatchNos(String.join(",",alreadyList));
                                dispatchService.updateOrderDispatchTaskById(orderDispatchTask);
                            }else{
                                isSuccess = false;
                                orderDispatchTask.setFailureReason(returnData.getMsg());
                                orderDispatchTask.setDispatchTaskStatus(OrderDispatchTask.DispatchTaskStatus.fail);
                                dispatchService.dispatchFailRestore(loginUser, dispatchOrder.getId());
                                dispatchService.updateOrderDispatchTaskById(orderDispatchTask);
                                break;
                            }
                        }
                        if (isSuccess){
                            orderDispatchTask.setDispatchTaskStatus(OrderDispatchTask.DispatchTaskStatus.complete);
                            dispatchService.updateOrderDispatchTaskById(orderDispatchTask);
                        }
                    }
                }
            }catch (Exception e){
                logger.error("定时任务 自动派单 执行失败！" + e.getMessage());
            }finally {
                RedisClient.getInstance().hdel("TIMER_TASK_KEY", "taskDispatchOrder");
            }
        }
    }

    /**
     * 定时任务 自动评价
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void autoOrderAppraise() {
        try {
            orderAppraiseService.autoOrderAppraise();
        } catch (Exception e) {
            logger.error("定时任务 自动评价 执行失败！" + e.getMessage());
        }
    }

    /**
     * 定时任务 汇总自动清算
     */
    @Scheduled(fixedDelay = 3 * 1000)
    public void gatherAutoSure() {
        String suc = RedisClient.getInstance().hget("TIMER_TASK_KEY", "gatherAutoSure");
        if (suc==null) {
            RedisClient.getInstance().hset("TIMER_TASK_KEY", "gatherAutoSure","true");
            try {
                gatherService.gatherAutoSure();
            } catch (Exception e) {
                logger.error("定时任务 汇总自动清算 执行失败！" + e.getMessage());
            }finally {
                RedisClient.getInstance().hdel("TIMER_TASK_KEY", "gatherAutoSure");
            }
        }
    }

    /**
     * 定时任务 24小时未生成运单得抢单自动作废
     */
    @Scheduled(fixedDelay = 3 * 1000)
    public void autoScrapRobOrder() {
        try {
            robService.autoScrapRobOrder();
        } catch (Exception e) {
            logger.error("定时任务 24小时未生成运单得抢单自动作废 执行失败！" + e.getMessage());
        }
    }

    /**
     * 定时任务 货源自动下线
     */
    @Scheduled(fixedDelay = 3 * 1000)
    public void timerRecallGoodsOrder() {
        try {
            goodsService.timerRecallGoodsOrder();
        } catch (Exception e) {
            logger.error("定时任务 货源自动下线 执行失败！" + e.getMessage());
        }
    }

    /**
     * 定时任务 自动确认回执
     */
//     @Scheduled(fixedDelay = 3 * 1000)
    public void autoConfirmReceipt() {
        try {
            transitService.autoConfirmReceipt();
        } catch (Exception e) {
            logger.error("定时任务 自动确认回执 执行失败！" + e.getMessage());
        }
    }

}
